<template>
  <a-card
    :bordered="false"
    :bodyStyle="{ padding: '24px 16px', height: '100%' }"
    id="aCardPosition"
  >
    <div class="table-page-search-wrapper">
      <a-row :gutter="48">
        <a-form-model layout="inline" v-model="queryParams">
          <a-col :md="8" :sm="24">
            <a-form-model-item label="所在校区：">
              <a-select
                v-model="queryParams.structures_id"
                placeholder="请选择校区"
                allowClear
                style="width:80%;"
              >
                <a-select-option
                  v-for="(item,index) in structureList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="关联课程">
              <a-select
                v-model="queryParams.course_id"
                placeholder="请选择课程"
                allowClear
                style="width:80%;"
              >
                <a-select-option
                  v-for="(item,index) in courseList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="班级教师">
              <a-select
                v-model="queryParams.teacher_id"
                placeholder="请选择教师"
                allowClear
                style="width:80%"
              >
                <a-select-option
                  v-for="(item,index) in teacherList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-form-model>

        <a-form-model v-if="showSearch" layout="inline" style="margin-top:10px;">
          <a-col :md="8" :sm="24">
            <a-form-model-item label="上课教室：">
              <a-select
                v-model="queryParams.classroom_id"
                allowClear
                placeholder="请选择教室"
                style="width:80%"
              >
                <a-select-option
                  v-for="(item,index) in classroomList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="上课班级：">
              <a-select
                v-model="queryParams.class_id"
                allowClear
                placeholder="请选择上课班级"
                style="width:80%"
              >
                <a-select-option
                  v-for="(item,index) in classList"
                  :key="index"
                  :value="item.id"
                  v-if="!item.finish_time"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="上课学员：">
              <a-select
                show-search
                v-model="queryParams.student_id"
                allowClear
                placeholder="请输入学员姓名并选择关联学员"
                style="width:80%"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                @search="searchStudent"
              >
                <a-select-option
                  v-for="(item,index) in studentList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-form-model>
      </a-row>
    </div>
    <a style="cursor:pointer" v-if="showSearch" @click="more" id="moreButton">
      收起
      <a-icon type="up"></a-icon>
    </a>
    <a style="cursor:pointer" v-if="!showSearch" @click="more" id="moreButton">
      展开
      <a-icon type="down"></a-icon>
    </a>
    <div style="display:flex;">
      <div style="width:40%;display:flex;align-items: center;">
        <a-button @click="exportTable">导出课表</a-button>
        <div style="margin-left:20px;width: 210px;">
          双击下方表格空白处可排课
        </div>
      </div>
      <div class="action_button">
        <a-button @click="getLastWeek">上一周</a-button>
        <a-date-picker v-model="today" class="datePicker" />
        <a-button @click="getNextWeek">下一周</a-button>
      </div>
    </div>
    
    <a-spin :spinning="loading">
      <div class="timeTable">
        <div class="table_head">
          <div></div>
          <div
            class="weekNum"
            v-for="(item,index) in data.title"
            :key="index"
            :class="{'activeColor':item.date==nowTime}"
          >{{item.weekName}}({{item.date}})</div>
        </div>
        <div class="table_body">
          <div class="table_body_line" v-for="(item,index) in data.teacher" :key="index">
            <div class="teacher_name">
              <a :title="item.name" style="color:#666;cursor:default">{{item.name}}</a>
            </div>
            <div class="having_class" v-for="(j,k) in item.classInfo" :key="k" @dblclick="addlessonTable(j)">
              <div class="classInfoLine" v-for="(m,n) in j" :key="n" v-if="j.length>0">
                <a-popover placement="rightTop" arrowPointAtCenter>
                  <template slot="content">
                    <div class="orderNAMEinfo" style="overflow:hidden !important;">
                      <p class="popoverTag" style="color:rgb(51,51,51);">所在校区：{{m.structure_name}}</p>
                      <p class="popoverTag" style="color:rgb(51,51,51);">班级：{{m.class}}</p>
                      <p
                        class="popoverTag"
                        style="color:rgb(51,51,51);"
                      >上课时间：{{m.date}}&nbsp;&nbsp;{{m.time_interval}}</p>
                      <p class="popoverTag" style="color:#888">
                        <a-icon
                          :component="classing"
                          style="margin-right:5px; color:#bfbfbf;font-size:16px;"
                        ></a-icon>
                        课程：{{m.course}}
                      </p>
                      <p class="popoverTag" style="color:#888">
                        <a-icon
                          :component="classing"
                          style="margin-right:5px; color:#bfbfbf;font-size:16px;"
                        ></a-icon>
                        老师：
                        {{m.teachers.toString()}}
                      </p>
                      <p class="popoverTag" style="color:#888">
                        <a-icon
                          :component="classroom"
                          style="margin-right:5px; color:#bfbfbf;font-size:16px;"
                        ></a-icon>
                        教室：{{m.field_name}}
                      </p>

                      <p class="popoverTag" style="color:#888">
                        <a-icon
                          type="team"
                          style="margin-right:5px; color:#bfbfbf;font-size:16px;"
                        />
                        学生人数：{{m.student.length}}
                      </p>
                      <div class="popoverBtmLine">
                        <a @click="orderName(m)" v-if="m.type=='schedule'">点名</a>
                        <a @click="lookInfo(m)">查看详情</a>
                      </div>
                      <div class="alreadyOrderName" v-if="m.type=='call'">
                        <img src="~@/assets/orderName.png" alt />
                      </div>
                      <div class="alreadyOrderName" v-else-if="m.type!=='call'&&m.class_id==0">
                        <img src="~@/assets/tryListen.png" alt />
                      </div>
                    </div>
                  </template>
                  <a-button
                    class="button__"
                    :style="{color:'white', background:m.color==0?'rgb(120, 191, 250)':m.color==1?'rgb(250, 187, 124)':m.color==2?'rgb(152, 217, 139)':m.color==3?'rgb(66, 214, 195)':m.color==4?'rgb(245, 146, 200)':m.color==5?'rgb(182, 161, 245)':'',
                    }"
                  >
                    <span v-if="m.class">{{m.class}}</span>
                    <span v-if="m.time_interval">，</span>
                    <span v-if="m.time_interval">{{m.time_interval}}</span>
                  </a-button>
                </a-popover>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-spin>
    <lesson-drawer ref="drawer" :structure_name="structureName" @deleteLesson="getTableList(today)"></lesson-drawer>
     <paike ref="paike" @addSuccess="creatPaike"/>
  </a-card>
</template>

<script>
import { lessonTableTeacherList,exportTimeTable } from '@/api/lessonTable'
import lessonDrawer from '@/components/lessonTableDrawer'
import moment from 'moment'
import { classroom, classing } from '@/core/icons'
import { campusList } from '@/api/structure'
import { classroomList } from '@/api/classroom'
import { coursesList } from '@/api/courseCharge'
import { teacherList } from '@/api/teacher'
import { classList } from '@/api/class'
import { studentList } from '@/api/student'
import paike from '@/components/paiKeModel'
export default {
  components: {
    lessonDrawer,
    paike
    // lessonTableTimeList
  },
  data() {
    return {
      nowTime:moment().format('YYYY-MM-DD'),
      loading: false,
      classroom,
      classing,
      structureName: '--',
      data: {
        title: [],
        teacher: [
          {
            name: '李老师',
            classInfo: [{}, {}, {}, {}, {}, { class_name: '体育课', start_time: '11:00', class_name: '一年级1班' }, {}],
          },
          {
            name: '王老师',
            classInfo: [
              {},
              {},
              {},
              { class_name: '英语课', start_time: '7:00', class_name: '一年级2班' },
              {},
              { class_name: '英语课', start_time: '9:00', class_name: '一年级3班' },
              {},
            ],
          },
          {
            name: '周老师',
            classInfo: [{}, {}, {}, {}, {}, { class_name: '语文课', start_time: '21:00', class_name: '一年级4班' }, {}],
          },
        ],
      },
      today: moment(),

      //搜索
      structureList: [],
      courseList: [],
      studentList: [],
      classList: [],
      teacherList: [],
      classroomList: [],
      queryParams: {},
      showSearch: false,
    }
  },
  created() {
    let today = this.formatTime()
    this.today = moment(today)
    campusList({
      school_id: this.$store.state.user.school,
      type: 1,
    }).then((res) => {
      this.structureList = res
    })
    coursesList({ pageSize: 999999, school_id: this.$store.state.user.school,is_enable: 1, }).then((res) => {
      this.courseList = res.data
    })
    classroomList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
      this.classroomList = res.data
    })
    teacherList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
      this.teacherList = res.data
    })
    classList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
      this.classList = res.data
    })
  },
  watch: {
    today(val) {
      this.getTableList(val)
    },
    queryParams: {
      deep: true, //深度监听设置为 true
      handler: function (newV, oldV) {
        this.getTableList(this.today)
      },
    },
  },
  methods: {
    creatPaike(){
      this.getTableList(this.today)
    },
    addlessonTable(data){
     if(data.length>0){
       this.start_date=moment(data[0].time)
      this.$refs.paike.form.start_time=this.start_date
     }
      let that=this
      this.$confirm({
        title: '是否创建排课？',
        onOk() {
           that.$refs.paike.showModel()
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
      
    },
    exportTable(){
        exportTimeTable(Object.assign(this.queryParams,{export_type:2})).then(res=>{
             window.location.href = res.url.url + res.url.path
          this.$message.success('导出成功')
        }).catch((err) => {
          this.loading = false
          this.$message.error(err.data.message || '导出失败，请刷新后重试')
        })
    },
    searchStudent(val) {
      let that = this
      if (this.timer != null) {
        clearTimeout(this.timer)
        this.timer = null
      } else {
        this.timer = setTimeout(function () {
          studentList({
            school_id: that.$store.state.user.school,
            pageSize: 999999999999,
            name: val,
          }).then((res) => {
            that.timer = null
            that.studentList = res.data
          })
        }, 500)
      }
    },
    more() {
      this.showSearch = !this.showSearch
    },
    getLastWeek() {
      let newDay = moment(this.today).format('YYYY-MM-DD')
      let lastWeekDay = new Date(new Date(newDay).getTime() - 168 * 60 * 60 * 1000)
      let theRealDay = this.formatTime(lastWeekDay)
      this.today = moment(theRealDay)
    },
    getNextWeek() {
      let newDay = moment(this.today).format('YYYY-MM-DD')
      let nextWeekDay = new Date(new Date(newDay).getTime() + 168 * 60 * 60 * 1000)
      let theRealDay = this.formatTime(nextWeekDay)
      this.today = moment(theRealDay)
    },
    getTableList(e) {
      this.loading = true
      let newDay = moment(e).format('YYYY-MM-DD')
      lessonTableTeacherList(
        Object.assign(this.queryParams, {
          date: newDay,
          school_id: this.$store.state.user.school,
        })
      )
        .then((res) => {
          this.loading = false
          this.data = res
        })
        .catch((err) => {
          this.loading = false
          this.$message.error(err.data.message || '获取数据失败，请刷新后重试')
        })
    },
    formatTime(e) {
      let date
      if (e) {
        date = new Date(e)
      } else {
        date = new Date()
      }
      let seperator1 = '-'
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      let today = year + seperator1 + month + seperator1 + strDate
      return today
    },
    //抽屉
    lookInfo(e) {
      if (e.structure_name) {
        this.structureName = e.structure_name
      }
      this.$refs.drawer.showDrawer(e)
    },
    orderName(data) {
      if (data.schedule_type == '1v1' && data.class_id == 0) {
        this.$router.push({
          name: 'orderName',
          query: {
            is1v1: data.id,
            type: data.type,
            time: data.date,
            class_id: 0,
          },
        })
      } else {
        this.$router.push({
          name: 'orderName',
          query: {
            class_id: data.class_id,
            schedules_id: data.id,
            date: data.time,
            classStartTime: data.class_start_time,
            classEndTime: data.class_end_time,
            teacher: data.teacher_ids,
            classroom: data.classroom_id,
            content: data.content,
          },
        })
      }
    },
  },
}
</script>

<style lang="less">
.ant-popover-inner-content {
  padding: 0;
}
</style>
<style lang="less" scoped>
#aCardPosition {
  position: relative;
}
#moreButton {
  position: absolute;
  top: 34px;
  right: 20px;
}
.orderNAMEinfo {
  padding-top: 20px;

  position: relative;
  .popoverTag {
    font-size: 14px;
    margin-bottom: 8px;
    padding: 0 20px;
  }

  .alreadyOrderName {
    position: absolute;
    top: -1px;
    right: -1px;
  }
}
.ant-popover-inner-content {
  padding: 0;
}
.popoverBtmLine {
  margin-top: 10px;
  border-top: 1px solid #e8e8e8;
  min-width: 300px;
  padding: 10px;
  line-height: 24px;
  text-align: center;
  display: flex;
  font-size: 16px;
  font-weight: 500;
  justify-content: space-around;
}
.action_button {
  .datePicker {
    margin: 0 10px;
  }
}
.timeTable {
  margin: 15px 0;
  border: 1px solid #e8e8e8;
  .table_head {
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    div {
      padding: 15px 0;
    }
    .weekNum {
      width: 220px;
      text-align: center;
      border-left: 1px solid #e8e8e8;
    }
    div:first-child {
      width: 100px;
    }
  }
  .table_body {
    .table_body_line {
      display: flex;
      border-bottom: 1px solid #e8e8e8;
      height: 180px;
      div {
        text-align: center;
      }
      .teacher_name {
        width: 100px;
        line-height: 180px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .having_class {
        width: 220px;
        padding: 15px 0px;
        height: 180px;
        overflow-y: auto;
        border-left: 1px solid #e8e8e8;
        .classInfoLine {
          margin: 0 10px 5px;

          .button__ {
            display: block !important;
            max-width: 190px;
            height: 30px;
            font-size: 12px;
            border-radius: 2px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
    .table_body_line:last-child {
      border-bottom: none;
    }
  }
}
.activeColor{
  color: #1890ff;
}
</style>